package com.maycurobj.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maycurobj.configuration.ConfInfo;
import com.maycurobj.pojo.EhrEmployeeInfo;
import com.maycurobj.service.http.HttpAPIService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.maycurobj.util.NormalUtil.*;

/**
 * ehr接口服务
 */
@Service
@Slf4j
public class EhrService {

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private HttpAPIService httpAPIService;


    // Token缓存，避免重复获取
    private String cachedToken;
    private long tokenExpireTime = 0;
    private static final long TOKEN_CACHE_TIME = 3600000; // 1小时缓存时间

    /**
     * 获取ehr token，带缓存机制
     */
    private String getToken() {
        // 检查缓存是否有效
        if (cachedToken != null && System.currentTimeMillis() < tokenExpireTime) {
            return cachedToken;
        }

        String reqUrl = String.format("%sOAuth/Token", this.confInfo.getEhrurl());
        String req = String.format("secret=%s&tenant_id=%s&grant_type=%s&app_id=%s",
                this.confInfo.getEhrsecret(),
                this.confInfo.getEhrtenantid(),
                this.confInfo.getEhrgranttype(),
                this.confInfo.getEhrappid());

        try {
            String rsp = this.httpAPIService.doPostForEhr(reqUrl, req);
            JSONObject jsonObject = JSON.parseObject(rsp);
            if (!jsonObject.containsKey("access_token")) {
                log.error("EHR token获取失败，响应中不包含access_token: {}", rsp);
                return null;
            }

            // 缓存token
            cachedToken = jsonObject.getString("access_token");
            tokenExpireTime = System.currentTimeMillis() + TOKEN_CACHE_TIME;
            log.info("EHR token获取成功，已缓存");
            return cachedToken;
        } catch (Exception ex) {
            log.error("EHR token获取异常", ex);
            return null;
        }
    }

    /**
     * 使用窗口方式获取指定范围内的员工数据
     * 内部程序 直接从service引用,不使用控制器
     * 返回的用户对象为EHR的客户对象
     * 返回map（1、usermap(userid+jobnumber) 2.employeeInfo (ehrEmployeeInfo对象list)）
     */
    public Map<String, Object> getEHRUserInfo() {
        StringBuilder nullForPoName = new StringBuilder();
        StringBuilder nullForMobile = new StringBuilder();
        String reqUrl = this.confInfo.getEhrurl() + "tenantbase/v1/" + this.confInfo.getEhrtenantid() + "/employee/timewindow/search";

        // 分页参数
        int pageIndex = 0;
        int pageSize = 100;
        int total = 0;
        boolean hasMoreData = true;

        // 创建接收json组
        JSONArray rsqArray = new JSONArray();

        // 获取token，避免在循环中重复获取
        String token = getToken();
        if (token == null) {
            log.error("无法获取EHR token，终止数据获取");
            return createEmptyResult();
        }

        // 优化分页查询逻辑
        while (hasMoreData) {
            JSONObject reqJson = createPageRequest(pageIndex + 1, pageSize);

            try {
                String rspStr = this.httpAPIService.doPost(reqUrl, reqJson.toJSONString(), token);
                JSONObject responseJson = JSONObject.parseObject(rspStr);

                if (responseJson.getJSONArray("Data") != null && !responseJson.getJSONArray("Data").isEmpty()) {
                    // 获取总数（只在第一次获取）
                    if (pageIndex == 0) {
                        total = responseJson.getIntValue("Total");
                        log.info("EHR员工总数: {}", total);
                    }

                    JSONArray dataArray = responseJson.getJSONArray("Data");
                    rsqArray.addAll(dataArray);

                    // 判断是否还有更多数据
                    hasMoreData = (pageIndex + 1) * pageSize < total;
                    pageIndex++;

                    log.debug("已获取第{}页数据，当前总数: {}", pageIndex, rsqArray.size());
                } else {
                    // 没有更多数据
                    hasMoreData = false;
                    log.info("EHR分页查询完成，无更多数据");
                }

            } catch (Exception ex) {
                log.error("EHR分页查询异常，页码: {}", pageIndex + 1, ex);
                hasMoreData = false; // 发生异常时停止查询
            }
        }
        //输出获取到的用户List
        log.info("获取到EHR用户list：{}", rsqArray.size());
        //组装员工map
        Map<String, String> userMap = new HashMap<>();
        //转ehremployeeinfo 对象 (需含转换字段) key=userid value=jobnumber
        List<EhrEmployeeInfo> ehrEmployeeInfos = new ArrayList<>();
        nullForPoName.append("用户上级不存在的对象：");
        nullForMobile.append("用户没有钉钉号码：");
        for (int i = 0; i < rsqArray.size(); i++) {
            JSONObject jsonObj = rsqArray.getJSONObject(i);
            JSONObject jsonBasic = jsonObj.getJSONObject("BasicInfos");
            JSONArray jsonServices = jsonObj.getJSONArray("ServiceInfos");
            JSONObject jsonService = jsonServices.getJSONObject(0);
            if (!jsonService.getBoolean("IsCurrentRecord")) {
                continue;
            }
            EhrEmployeeInfo ehrEmployeeInfo = new EhrEmployeeInfo();
            ehrEmployeeInfo.setEmail(jsonBasic.getString("Email"));
            ehrEmployeeInfo.setName(jsonBasic.getString("Name"));
            ehrEmployeeInfo.setUserID(String.valueOf(jsonBasic.getLongValue("UserID")));
            ehrEmployeeInfo.setJobNumber(jsonService.getString("JobNumber"));
            ehrEmployeeInfo.setEmploymentType(jsonService.getString("EmploymentType"));
            ehrEmployeeInfo.setPoid(String.valueOf(jsonService.getLongValue("POIdEmpAdmin")));

            if (!jsonService.containsKey("POIdEmpAdmin")) {
                nullForPoName.append(jsonBasic.getString("Name") + ",");
            }
            //记录没有钉钉号码的人员
            if (!jsonService.containsKey("extdingdinghaoma_107502_1614598274")) {
                nullForMobile.append(jsonBasic.getString("Name") + ",");
            }
            //转换本请求的对象属性
            ehrEmployeeInfo.setZhudi(String.valueOf(jsonService.getString("extzhudi_107502_1469764567")));
            ehrEmployeeInfo.setAccountNum(jsonBasic.getString("extbankcard_107502_377022026"));
            ehrEmployeeInfo.setBackInfo(jsonBasic.getString("extgongzikayinhang_107502_420006705"));
            ehrEmployeeInfo.setMobilePhone(jsonService.getString("extdingdinghaoma_107502_1614598274"));    //钉钉号码

            ehrEmployeeInfos.add(ehrEmployeeInfo);

            //加入到usermap中 key=ehruserid value=ehr工号
            userMap.put(String.valueOf(jsonBasic.getLongValue("UserID")), jsonService.getString("JobNumber"));
        }
        Map<String, Object> reMap = new HashMap<>();
        //处理ehrArray细节
        handlerUserContrant(ehrEmployeeInfos);

        reMap.put("userMap", userMap);
        reMap.put("ehrObject", getEHRUserItem(userMap, ehrEmployeeInfos));
        reMap.put("nullForPoName", nullForPoName.toString());
        reMap.put("nullForMobile", nullForMobile.toString());
        log.info("总共记录：{}", ehrEmployeeInfos.size());

        return reMap;
    }

    /**
     * 对ehrEmployeeInfos 赋值上级属性
     * @param userTitle
     * @param lists
     * @return
     */
    private List<EhrEmployeeInfo> getEHRUserItem(Map<String, String> userTitle, List<EhrEmployeeInfo> lists) {
        if (lists.isEmpty()) {
            return null;
        }
        for (EhrEmployeeInfo ehr : lists) {
            if (StringUtils.isNotBlank(ehr.getPoid())) {
                ehr.setPoName(userTitle.containsKey(ehr.getPoid()) ? userTitle.get(ehr.getPoid()) : "");
            }
        }
        return lists;
    }


    /**
     * 批量获取员工合同,并调整ehrUserArray对象结构
     *
     * @return
     */
    public void handlerUserContrant(List<EhrEmployeeInfo> ehrEmployeeInfoList) {
        // 分页参数
        int pageIndex = 0;
        int pageSize = 300;
        int total = ehrEmployeeInfoList.size();
        boolean hasMoreData = true;

        JSONArray allArray = new JSONArray();
        while (hasMoreData) {
//            log.info("页面情况pageIndex===>{},pageSize====>{}", pageIndex, pageSize);
            List<String> ids = new ArrayList<>();
            int startIndex = pageIndex * pageSize;
            int endIndex = Math.min(startIndex + pageSize, total);
            
            for (int i = startIndex; i < endIndex; i++) {
                EhrEmployeeInfo ehrEmployeeInfo = ehrEmployeeInfoList.get(i);
                ids.add(ehrEmployeeInfo.getUserID());
            }
            
            // 检查是否还有更多数据
            if (endIndex >= total) {
                hasMoreData = false;
            }
            //组配完毕
            String reqUrl = this.confInfo.getEhrurl() + "tenantbase/v1/" + this.confInfo.getEhrtenantid() + "/contract/ids/search";
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Ids", ids);
            jsonObject.put("Columns", new String[]{"FirstPartyCode", "UserID", "JobNumber", "status", "FirstParty"});
            try {
                String rspStr = this.httpAPIService.doPost(reqUrl, jsonObject.toJSONString(), getToken());
                JSONArray res = JSONArray.parseArray(rspStr);
                allArray.addAll(res);
                pageIndex++;
            } catch (Exception e) {
                log.error("批量获取员工合同信息异常，页码: {}", pageIndex, e);
                break;
            }
        }

        //处理所有的数据记录
        for (Object obj : allArray) {
            JSONObject jsonObject = (JSONObject) obj;
            if (jsonObject.getInteger("status") == 1) {
                //有效处理
                String firstParty=jsonObject.getString("FirstParty");
                String contantCropName = convertFirstParty(firstParty);
                String userId = jsonObject.getString("UserID");
                for (EhrEmployeeInfo dto : ehrEmployeeInfoList) {
                    if (dto.getUserID().equals(userId)) {
                        dto.setDefaultLegalEntityBizCode(contantCropName);
                        dto.setBizCodeName(firstParty);
                    }
                }
                //调整的ehrArray对象中
            }
        }
    }

    /**
     * 合同转换比较
     */
    private String convertFirstParty(String firstParty) {
        switch (firstParty) {
            case "浙江博圣生物技术股份有限公司":
                return "ELC21102113QULS74";
            case "杭州贝安云科技有限公司":
                return "ELC2111041NL9WXS0";
            case "宁波贝生医疗器械有限公司":
                return "ELC2111041NL9X79C";
            case "杭州贝生医疗器械有限公司":
                return "ELC2111041NL9X8U8";
            case "上海恩允实业有限公司":
                return "ELC2111041NL9XC00";
            case "杭州博圣云鼎冷链物流有限公司":
                return "ELC2111041NL9XF5S";
            case "南京卓恩生物技术有限公司":
                return "ELC2111041NL9XLHC";
            case "杭州贝可医疗器械有限公司":
                return "ELC2111041NL9XON4";
            case "杭州杰毅麦特医疗器械有限公司":
                return "ELC2111041NL9Y1A8";
            case "杭州博圣医学检验实验室有限公司":
                return "ELC2111041NL9Y2V4";
            case "湖北奥博特生物技术有限公司":
                return "ELC2111041NL9Y96O";
            case "湖南杰毅麦特生物科技有限公司":
                return "ELC2202241A41OKU8";
            case "上海龙幸医疗设备有限公司":
                return "ELC2207191LUJRABK";
            case "北京贝康医学检验所有限公司":
                return "ELC68249692632259658";
            default:
                return "ELC21102113QULS74";
        }
    }

    /**
     * 创建分页请求对象
     */
    private JSONObject createPageRequest(int pageIndex, int pageSize) {
        JSONObject reqJson = new JSONObject(true);
        reqJson.put("IsGetLatestRecord", true);
        reqJson.put("StartTime", "2017-10-29T15:13:33.031Z");
        reqJson.put("StopTime", getGMTDateTime());
        reqJson.put("WithDisabled", false);
        reqJson.put("WithDeleted", false);
        reqJson.put("PageIndex", pageIndex);
        reqJson.put("PageSize", pageSize);
        reqJson.put("Columns", new String[]{
                "EmploymentType", "UserID", "Email", "JobNumber", "Name",
                "extgongzikayinhang_107502_420006705", "extbankcard_107502_377022026",
                "extdjls_107502_1356399109", "extzhudi_107502_1469764567",
                "POIdEmpAdmin", "extdingdinghaoma_107502_1614598274", "IsCurrentRecord", "OIdJobLevel",
                "extguanlizhiji_107502_1415703452,FirstPartyLookup"
        });
        return reqJson;
    }

    /**
     * 创建空结果对象
     */
    private Map<String, Object> createEmptyResult() {
        Map<String, Object> emptyMap = new HashMap<>();
        emptyMap.put("userMap", new HashMap<String, String>());
        emptyMap.put("ehrObject", new ArrayList<EhrEmployeeInfo>());
        emptyMap.put("nullForPoName", "无数据");
        emptyMap.put("nullForMobile", "无数据");
        return emptyMap;
    }

    /**
     * 获取单一 员工信息
     */
    @Deprecated
    public String getSingleUser(String email) {
        String reqUrl = this.confInfo.getEhrurl() + "tenantbase/v1/" + this.confInfo.getEhrtenantid() + "/employee/seviceinfo/email/search";
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Email", email);
        jsonObject.put("Columns", new String[0]);
        try {
            String rspStr = this.httpAPIService.doPost(reqUrl, jsonObject.toJSONString(), getToken());
            JSONObject rspJson = JSONObject.parseObject(rspStr);
            if (!Objects.isNull(rspJson.getString("Data"))) {
                //返回不为空,调用获取用户信息
                return rspJson.getString("Data");
            } else {
                log.error("--EHR用户查询异常");
                return null;
            }

        } catch (Exception ex) {
            log.error("获取单一员工信息异常，邮箱: {}", email, ex);
        }
        return null;
    }


}
